<template>
  <div class="app-container">
    <!-- 查看服务 -->
    <!-- <span class="serviceInfo">{{ check_status| filterNull }}</span> -->
    <h5 class="titleInfo">基础信息</h5>
    <el-form ref="detailsList" :model="detailsList" label-width="150px" :rules="rules">
      <!-- 查询模块 -->
      <div class="formDiv">
        <el-row>
          <!-- <el-col :span="24"> -->
          <el-form-item label="服务名称" prop="service_name">
            <el-input
              v-model="detailsList.service_name"
              placeholder=" 最少输入1个字，最多输入32个字 "
              style="width:100%;"
            />
            <span class="spanINfo">商品不支持发货，需用户店内自提</span>
          </el-form-item>
          <!-- </el-col> -->
          <!-- <el-col :span="24"> -->
          <el-form-item label="服务分类" prop="category_id">
            <el-cascader  v-model="detailsList.category_id" :options="options" />
            <!-- <el-select v-model="detailsList.category_id" placeholder="更换分类">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->
          </el-form-item>
          <!-- </el-col> -->
          <el-col :span="12">
            <el-form-item label="服务描述" prop="service_desc">
              <el-input
                v-model="detailsList.service_desc"
                size="large"
                type="textarea"
                :rows="4"
                placeholder="最少输入1个字，最多输入200个字 "
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务售价" prop="price">
              <el-input v-model="detailsList.price" placeholder="请输入服务售价" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务原价" prop="origin_price">
              <el-input v-model="detailsList.origin_price" placeholder="请输入服务原价" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务分佣比例" prop="division_rate" show-message>
              <el-input
                v-model.number="detailsList.division_rate"
                placeholder="请输入分佣比例"
                type="text"
              />
              <span class="spanINfo">1.分佣为平台推广佣金；</span>
              <span class="spanINfo">2.分佣比列为 20% - 100%区间；</span>
              <span class="spanINfo">3.最终以顾客实付款进行相关佣金分配和成本结算；</span>
              <span class="spanINfo">4.佣金比例越高，推广效果越好。</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务排序" prop="sort">
              <el-input v-model="detailsList.sort" placeholder="数值越大，排序越靠前" />
              <span class="spanINfo">数值越大，排序越靠前，商品在个人店铺内的排序</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="divBar" />
      <!-- 服务图片 -->
      <h5 class="titleInfo">服务图片</h5>
      <div class="uploadImgInfo">
        <el-form-item label prop="service_image_ids">
          <newUpload ref="uploadImg" :file-num="5" :size-number="2" :file-list="fileList" />
          <span class="spanINfo">服务主图为展示的第一张图片，添加上传图片，最多可添加5张，点击图片左右滑动进行排序（除主图外）</span>
          <span class="spanINfo">请上传小于2M图片，格式为jpg、png、jpeg</span>
        </el-form-item>
      </div>
      <div class="divBar" />
      <!-- 服务详情 -->
      <h5 class="titleInfo">服务详情</h5>
      <div id="wangeditor">
        <!-- 富文本编辑器 -->
        <el-row>
          <el-col :span="16">
            <el-form-item>
              <Tinymce v-model="detailsList.service_content" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="divBar" />
      <!-- 购买须知 -->
      <h5 class="titleInfo">购买须知</h5>
      <el-row>
        <el-col :span="24">
          <el-form-item label="预约信息" prop="appointment_hour">
            <template>
              <el-radio v-model="radio" label="1">无需预约，如遇高峰时段需要排队</el-radio>
              <el-radio v-model="radio" label="2">
                请您提前
                <el-input
                  v-model="detailsList.appointment_hour"
                  style="width:25%;"
                  type="text"
                  size="small"
                  placeholder="几小时"
                />小时预约
              </el-radio>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="规则提示" prop="rule_msg">
            <el-input
              v-model="detailsList.rule_msg"
              size="medium"
              type="textarea"
              :rows="4"
              placeholder="最少输入1个字，最多输入200个字 "
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="温馨提示" prop="warm_msg">
            <el-input
              v-model="detailsList.warm_msg"
              size="medium"
              type="textarea"
              :rows="4"
              placeholder="最少输入1个字，最多输入200个字 "
            />
          </el-form-item>
        </el-col>-->
        <el-col :span="12">
          <el-form-item label="温馨提示" prop="warm_msg">
            <!-- <Tinymce v-model="detailsList.warm_msg" /> -->
            <el-input
              v-model="detailsList.warm_msg"
              type="textarea"
              :rows="4"
              style="margin:20px 0"
              placeholder="最少输入1个字，最多输入200个字 "
            />
          </el-form-item>
        </el-col>
        <!-- <span v-show="submitInfoVisible" class="submitInfo">*您有内容未填写，请填写后再次提交审核</span> -->
      </el-row>
    </el-form>
    <div class="listDiv">
      <!-- 提交审核按钮 -->
      <el-button type="primary" class="submitBtn" @click="submitForm('detailsList')">提交审核</el-button>
    </div>
  </div>
</template>

<script>
import serverList from '@/api/serverList'
import phoneReg from '@/utils/validate'
import newUpload from '@/components/imgUpload/index'
import Tinymce from '@/components/Tinymce'

export default {
  name: 'ServerAdd',
  components: { newUpload, Tinymce },
  filters: {
    filterNull(e) {
      switch (e) {
        case 1:
          return '审核中'
          break
        case 2:
          return '审核未通过'
          break
        default:
          return '审核通过'
          break
      }
    },
    filterClass(e) {
      if (e) {
        return '二级分类'
      } else {
        return e
      }
    }
  },
  data() {
    // 售价校验
    var validatePrice = (rule, value, callback) => {
      if (value < Number(this.detailsList.price)) {
        callback(new Error('售价必须小于原价!'))
        this.warningStatus('售价必须小于原价!')
      } else {
        callback()
      }
    }
    // 服务分佣比例验证
    var validateIdentity = (rule, value, callback) => {
      const isRate = /^([2-9][0-9]|100)$/
      if (!value) {
        callback(new Error('请输入分佣比例'))
        this.warningStatus('请输入分佣比例!')
      } else if (this.detailsList.division_rate == '' || !isRate.test(value)) {
        callback(new Error('请输入正确分佣比例'))
        this.warningStatus('请输入区间为20-100的分佣比例!')
      } else {
        callback()
      }
    }
    // 名称验证
    var projectName = (rule, value, callback) => {
      const reg1 = new RegExp("[`!@#$^&*|':;',.<>/?~！@#￥……&*——|‘；：']")
      const reg2 = /(^\_)|(\__)|(\_+$)/
      const reg3 = /^\d+\d+\d$/
      if (!value) {
        callback(new Error('请输入名称'))
      } else if (reg1.test(value)) {
        callback(new Error('名称不能有特殊字符'))
      } else if (reg2.test(value)) {
        callback(new Error('名称首尾不能出现下划线'))
      } else if (reg3.test(value)) {
        callback(new Error('名称不能全为数字'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false,
      tableLoading: true,
      submitInfoVisible: false,
      dates: [],
      // 审核状态
      check_status: '1',
      // 服务分类数据
      options: [],

      // 提交数据列表
      detailsList: {
        service_name: '',
        category_id: [],
        service_desc: '',
        origin_price: '',
        price: '',
        division_rate: '',
        service_image_ids: '',
        service_content: '',
        appointment_hour: '0',
        rule_msg: '',
        warm_msg: '',
        sort: '0'
      },
      radio: '1',
      // table列表
      tableData: [],
      // 文本域信息
      textarea: '',
      editor: null,
      editorContent: '',
      // 预约信息
      checkList: [],
      imgList: [],
      fileList: [],
      // 提交表单验证规则
      rules: {
        service_name: [
          { required: true, validator: projectName, trigger: 'blur' },
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 32 个字符',
            trigger: 'blur'
          }
        ],
        category_id: [
          { required: true, message: '请选择服务分类', trigger: 'change' }
        ],
        service_desc: [
          { required: true, message: '请输入服务描述', trigger: 'blur' },
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字符',
            trigger: 'blur'
          }
        ],
        price: [{ required: true, message: '请输入服务售价', trigger: 'blur' }],
        origin_price: [
          {
            validator: validatePrice,
            required: true,
            message: '售价必须小于原价',
            trigger: 'blur'
          }
        ],
        division_rate: [
          {
            validator: validateIdentity,
            required: true,
            // message: "请输入分佣比例",
            trigger: 'blur'
          },
          { type: 'number', message: '只能输入数字', trigger: 'blur' }
        ],
        appointment_hour: [
          { required: true, message: '请选择', trigger: 'chnage' }
        ],
        rule_msg: [
          { required: true, message: '请输入规则提示', trigger: 'blur' },
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字符',
            trigger: 'blur'
          }
        ],
        warm_msg: [
          {
            required: true,
            message: '请输入温馨提示',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字符',
            trigger: 'blur'
          }
        ]
        // sort: [
        //   { type: "number", message: "只能输入数字", trigger: "blur" }
        // ]
      }
    }
  },
  inject: ['reload'],
  computed: {},
  created() {
    this.changeClass()
  },
  mounted() {},
  inject: ['reload'],
  methods: {
    // 更换分类
    changeClass() {
      serverList.changeClass().then(res => {
        // console.log(res.data)
        // const newArr = [];
        // res.data.forEach((item1, index) => {
        //   newArr.push({
        //     value: item1.value,
        //     label: item1.label
        //   });
        //   if (item1.children != null) {
        //     newArr[index]["children"] = [];
        //     item1.children.forEach(item2 => {
        //       newArr[index]["children"].push({
        //         value: item2.value,
        //         label: item2.label
        //       });
        //     });
        //   }
        // });
        this.options = res.data
      })
    },
    // 提交审核
    submitForm(e) {
      this.detailsList.service_image_ids = this.$refs.uploadImg.submitUpload()
      this.$refs[e].validate(valid => {
        if (valid) {
          const dataInfo = {
            service_name: this.detailsList.service_name,
            category_id: this.detailsList.category_id,
            service_desc: this.detailsList.service_desc,
            origin_price: this.detailsList.origin_price,
            price: this.detailsList.price,
            division_rate: this.detailsList.division_rate,
            service_image_ids: this.detailsList.service_image_ids.join(','),
            service_content: this.detailsList.service_content,
            appointment_hour: this.detailsList.appointment_hour,
            rule_msg: this.detailsList.rule_msg,
            warm_msg: this.detailsList.warm_msg,
            sort: this.detailsList.sort
          }
          serverList
            .addList(dataInfo)
            .then(res => {
              if (res.data.code == 200) {
                this.succStatus('提交成功')
                this.$router.push('/serverList')
                this.reload()
              } else {
                this.$message({
                  showClose: true,
                  message: res.data.msg,
                  type: 'warning'
                })
              }
              this.tableLoading = false
            })
            .catch(err => {
              this.errorStatus(err.msg)
              this.tableLoading = false
            })
        } else {
          this.submitInfoVisible = true
          this.warningStatus('有必填项未填，不能提交哦!')
          return false
        }
      })
    },
    // 弹窗组件
    eleMsg(txt, status) {
      this.$message({
        showClose: true,
        message: txt,
        type: status
      })
    },
    // 成功状态弹窗
    succStatus(txt, status) {
      this.eleMsg(txt, 'success')
    },
    // 失败状态弹窗
    errorStatus(txt) {
      this.eleMsg(txt, 'error')
    },
    // 警告状态弹窗
    warningStatus(txt) {
      this.eleMsg(txt, 'warning')
    },
    // 路由跳转
    toRoutes(e, userId) {
      const route = { name: e, query: { userId: userId }}
      this.$router.push(route)
    },
    // 改变页面条数
    handleSizeChange(val) {
      this.form.pageSize = val
      this.getList(this.form)
    },
    // 选择页数
    handleCurrentChange(val) {
      this.form.pageNum = val
      this.getList(this.form)
    },

    // 删除
    callFn(e) {
      this.tableData.splice(e, 1)
    },
    // confirm框
    eleConfirm(e) {
      this.$confirm(e.desc, e.title, {
        confirmButtonText: e.confirmBtnTxt,
        cancelButtonText: e.cancelBtnTxt,
        type: 'warning'
      })
        .then(() => {
          e.fn()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: e.catchInfo
          })
        })
    }
  }
}
</script>
<style scoped>
/* 主页列表样式 */
.listDiv {
  margin-bottom: 20px;
  padding: 0 20px;
}
/* 分页 */
.pagesCon {
  height: 40px;
  margin-top: 20px;
}
.pagesCon > div {
  float: right;
}
.app-container {
  padding: 0.1px !important;
}
.form {
  margin-left: 20px;
}
.elFormImg {
  width: 268px;
}
.submitInfo {
  color: red;
  padding: 20px;
}
.submitBtn {
  margin-top: 20px;
  margin-bottom: 20px;
}
/* 服务图片区域样式 */
/* .uploadImgInfo {
  margin-left: 20px;
}
#wangeditor {
  padding: 20px;
} */
/* 提示语样式 */
.spanINfo {
  display: block;
  color: #444;
}
</style>
